package org.doubango.FrCall.network;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.doubango.FrCall.AppConfig;
import org.doubango.FrCall.Utils.LogDebugger;

/**
 * HTTP连接封装
 * 
 */
public class HttpConnecter {

	/**
	 * Get method.
	 * 
	 * @param uri
	 *            the uri of http request
	 * @return the string returned.
	 * @throws ClientProtocolException
	 *             ClientProtocolException
	 * @throws IOException
	 *             IOException
	 */
	public static String get(String uri) throws ClientProtocolException,
			IOException {
		HttpClient httpClient = new DefaultHttpClient();
		// ContentEncodingHttpClient httpClient = new
		// ContentEncodingHttpClient();
		HttpGet httpGet = new HttpGet(uri);
		setHeader(httpGet);
		HttpResponse httpResponse = httpClient.execute(httpGet);
		int statusCode = httpResponse.getStatusLine().getStatusCode();

		if (statusCode >= 200 && statusCode < 400) {
			StringBuilder stringBuilder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					httpResponse.getEntity().getContent(), "UTF-8"));
			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
				stringBuilder.append(s);
			}
			reader.close();
			LogDebugger.println("HTTP GET:" + uri.toString());
			LogDebugger.println("Response:" + stringBuilder.toString());
			return stringBuilder.toString();
		}
		return null;
	}

	/**
	 * Post method.
	 * 
	 * @param uri
	 *            the uri of http request
	 * @param formparams
	 *            List<NameValuePair>
	 * @return the string returned.
	 * @throws ClientProtocolException
	 *             ClientProtocolException
	 * @throws IOException
	 *             IOException
	 */
	public static String post(String uri, List<NameValuePair> formparams)
			throws ClientProtocolException, IOException {

		HttpClient httpClient = new DefaultHttpClient();
		// ContentEncodingHttpClient httpClient = new
		// ContentEncodingHttpClient();
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
				"UTF-8");
		HttpPost httpPost = new HttpPost(uri);
		setHeader(httpPost);
		httpPost.setEntity(entity);
		HttpResponse httpResponse = httpClient.execute(httpPost);

		int statusCode = httpResponse.getStatusLine().getStatusCode();
		if (statusCode >= 200 && statusCode < 400) {
			StringBuilder stringBuilder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					httpResponse.getEntity().getContent(), "UTF-8"));
			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
				stringBuilder.append(s);
			}
			reader.close();
			LogDebugger.println("HTTP POST:" + uri.toString());
			LogDebugger.println("Response:" + stringBuilder.toString());
			return stringBuilder.toString();
		}
		return null;
	}

	/**
	 * Download file from server.
	 * 
	 * @param file
	 *            File
	 * @param uri
	 *            the uri of http request
	 * @return the result. true if download success.
	 * @throws IOException
	 *             IOException
	 */
	public static boolean download(File file, String uri) throws IOException {
		if (file.exists() && file.isDirectory()) {
			return false;
		}
		boolean flag = false;
		file.getParentFile().mkdirs();
		File tmpFile = new File(file.getAbsolutePath() + ".tmp");
		InputStream is = null;
		BufferedOutputStream bos = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			// ContentEncodingHttpClient httpClient = new
			// ContentEncodingHttpClient();
			HttpGet httpGet = new HttpGet(uri);
			setHeader(httpGet);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				tmpFile.createNewFile();
				is = httpResponse.getEntity().getContent();
				bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
				byte[] buffer = new byte[4096];
				int i = is.read(buffer);
				while (i != -1) {
					bos.write(buffer, 0, i);
					i = is.read(buffer);
				}
				tmpFile.renameTo(file);
				flag = true;
			}
		} catch (IOException ioe) {
			LogDebugger.exception(ioe.getMessage());
			throw ioe;
		} finally {
			if (bos != null) {
				bos.close();
			}
			if (is != null) {
				is.close();
			}
		}

		return flag;
	}

	private static void setHeader(HttpRequestBase httpGetOrPost) {
		if (httpGetOrPost != null) {
			httpGetOrPost.setHeader(AppConfig.USER_ID, "10004");
			
//			httpGetOrPost.setHeader(AuthConstants.REQUEST_HEADER_VERSION,
//					GameLive.VERSION);
//			httpGetOrPost.setHeader(AuthConstants.REQUEST_HEADER_SID,
//					GameLive.getUserSid());
//			httpGetOrPost.setHeader(AuthConstants.REQUEST_HEADER_GAME_ID,
//					GameLive.getGameId());
//			AuthProvider ahth = AuthCreator.create();
//			httpGetOrPost.setHeader(AuthConstants.REQUEST_HEADER_GAME_SEED,
//					ahth.getSeed());
//			httpGetOrPost.setHeader(AuthConstants.REQUEST_HEADER_GAME_SKEY,
//					ahth.getSkey());
		}
	}

}
